package com.smartstate.autoMaticControl.websocket;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.concurrent.*;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;


import com.alibaba.fastjson.JSON;
import com.smartstate.autoMaticControl.config.SpringUtil;
import com.smartstate.autoMaticControl.entity.WebSocketOnMessage;
import com.smartstate.common.web.exception.CommonException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;



/**
 * @author zhengkai.blog.csdn.net
 */
@ServerEndpoint(value = "/imserver/{userId}", decoders = { OmDecoder.class }, encoders = { OmEncoder.class })
@Component
public class WebSocketServer {

    static Log log=LogFactory.get(WebSocketServer.class);
    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,Session> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId="";

    private boolean flag = true;

    private boolean flag0 = true;

    ////存放每个任务的ScheduledFuture对象
    //private static ConcurrentHashMap<String, ScheduledFuture> taskMap = new ConcurrentHashMap<>();
    //
    ////存放每个造假数据任务的ScheduledFuture对象
    //private static ConcurrentHashMap<String, ScheduledFuture> taskMap0 = new ConcurrentHashMap<>();

    //    最佳线程数目 = （（线程等待时间+线程CPU时间）/线程CPU时间 ）* CPU数目
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(10);

    ScheduledExecutorService scheduledThreadPool0 = Executors.newScheduledThreadPool(10);

    private  DataRealTimeRunnable runnable=new DataRealTimeRunnable();

    private   DateTimeRunnable dateTimeRunnable = new DateTimeRunnable();



    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        this.session = session;
        this.userId=userId;

         if(webSocketMap.containsKey(userId)){
             webSocketMap.remove(userId);
             webSocketMap.put(userId,session);
         }else{
            webSocketMap.put(userId,session);
            //加入set中
            addOnlineCount();
            //在线数加1
        }

        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        // if (taskMap.get(userId) != null) {
        //     taskMap.get(userId).cancel(true);
        // }
        scheduledThreadPool.shutdown();
        log.info("删除读取Redis数据线程池");
        // if (getOnlineCount()==0){
        //     log.info("删除数据线程");
        //     taskMap0.clear();
        // }
        scheduledThreadPool0.shutdown();
        log.info("删除造假数据线程池");
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param webSocketOnMessage 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(WebSocketOnMessage webSocketOnMessage,Session session) {
        //log.info(runnable);
        //log.info("用户消息:"+userId+",报文:"+webSocketOnMessage);
         if(!checkObjAllFieldsIsNull(webSocketOnMessage)) {
             //redis数据
             //if (!taskMap0.containsKey(webSocketOnMessage.getDeviceId())) {
                 dateTimeRunnable.setWebSocketOnMessage(webSocketOnMessage);
                 if (flag0 == true) {
                     ScheduledFuture<?> scheduledFuture1 = scheduledThreadPool0.scheduleWithFixedDelay(dateTimeRunnable,
                             0,
                             1,
                             TimeUnit.SECONDS);
                     //taskMap0.put(webSocketOnMessage.getDeviceId(), scheduledFuture1);
                     flag0 = false;
                 }
             //}
             //实时发送到客户端的线程
             runnable.setSession(session,webSocketOnMessage);
             //deviceTypeRunnable.setSession(session,webSocketOnMessage);
             if (flag == true){
                 ScheduledFuture<?> scheduledFuture =
                         scheduledThreadPool.scheduleWithFixedDelay(runnable,
                                 0,
                                 1,
                                 TimeUnit.SECONDS);
                 //taskMap.put(userId, scheduledFuture);
             }
         }else {
             throw new CommonException("无法收到客户端请求数据！");
         }
    }
    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public synchronized void sendMessage(Object message) throws IOException {
            this.session.getBasicRemote().sendText(JSON.toJSONString(message));
    }


    /**
     * 发送自定义消息
     * */
    public static void sendInfo(Object message, Session session) throws IOException {
        session.getBasicRemote().sendText(JSON.toJSONString(message));
    }



    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }


    /**
     * 判断对象中属性值是否全为空
     *
     * @param object
     * @return
     */
    public static boolean checkObjAllFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
                    return false;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

}
